﻿#ifndef CWEBSOCKETCLIENT_H
#define CWEBSOCKETCLIENT_H

#include <QObject>
#include <QTimer>
#include <QtCore/QHash>
#include <QtCore/QByteArray>
#include <QWebSocket>
#include <QTimer>
#include <QUrl>
#include <QFile>

QT_FORWARD_DECLARE_CLASS(QWebSocket)

class CWebSocketClient : public QObject
{
    Q_OBJECT

public:
    explicit CWebSocketClient(QObject *parent = nullptr);
    ~CWebSocketClient();

    /// 打开指定地址的网络连接
    void Open(QUrl url);
    /// 关闭连接
    void Close(void);
    /// 发送字符串
    qint64 Send(QString msg);
    /// 得到连接的url
    inline QUrl getUrl(void) { return m_websocketurl; }

Q_SIGNALS:
    void closed();
    void socketmessage(CWebSocketClient *pwebsocket,QString message);
    void socketconnected(CWebSocketClient *pwebsocket);
    void socketdisconnected(CWebSocketClient *pwebsocket);

private Q_SLOTS:
    /// 处理字符串消息
    void onTextMessageReceived(QString message);
    /// 处理连接关闭
    void onDisconnected();
    /// 处理连接成功
    void onConnected();
    /// 处理心跳
    void handleWebSocketHeartTimeOut();
    /// 处理断开重连
    void handleWebSocketReconnect();

private:
    QWebSocket m_webSocket;                                             /**< 网络客户端 */
    QUrl m_websocketurl;                                                /**< 要连接的服务器地址 */
    QTimer m_WebSocketHeartTimeOutTimer,m_WebSocketReconnectTimer;      /**< 用于处理心跳和断开重连的定时器 */
};

class CWebSocketClientManager
{
public:
     CWebSocketClientManager();
     ~CWebSocketClientManager();

     /// 添加一个客户端
     bool addClient(QString clientName,CWebSocketClient* pClient);
     /// 得到一个客户端
     CWebSocketClient* getClient(QString clientName);
     /// 清除所有的客户端
     void clearAllClients(void);
     /// 清除指定的客户端
     bool deleteClient(QString clientName);
     /// 得到当前客户端的数量
     inline int getcount(void) { return m_WebSocketClients.size(); }

private:
    QHash<QString,CWebSocketClient*> m_WebSocketClients;
};

#endif // CWEBSOCKETCLIENT_H
